using System;
using System.Globalization;
using System.Collections;
using UnityEngine;
using UnityEngine.AI;
using System.Collections.Generic;
// 玩家控制器，管理角色的行为、状态转换等
public class EnemyController : CharacterBase<EnemyController>
{

    private Quaternion forward;
    private NavMeshAgent agent;
    // public GameObject uiManager;
    public float FadeTime = 4.2f; // 渐隐时长
    private Renderer[] _renders;           // 渲染器缓存
    private Collider[] _cols;              // 碰撞器缓存
    public float attackCooldown;
    public float rayDistance;
    public float moveDirection;

    protected override void onStart()
    {
        agent = GetComponent<NavMeshAgent>();
        InputSource = new AIReaderSource(gameObject, attackCooldown)
           .SetTransform(transform);
        characterStateMachine.Initialize(new CharacterIdleState<EnemyController>(this, characterStateMachine), CharacterAnimation);
    }
    protected override void Init()
    {
        _renders = GetComponentsInChildren<Renderer>();
        _cols = GetComponentsInChildren<Collider>();
    }

    public override void Die()
    {
        //怪物死亡 渐变消失
        foreach (var c in _cols) c.enabled = false;   // 关碰撞
        // 停物理
        // StartCoroutine(FadeAndDestroy());  // 开始渐隐并销毁
        GameManager.Instance.AddScore(10);   // 全局加分

        //死亡，通知ui控制器
        // uiManager.GetComponent<GameUIControl>().DieBool(1);
    }

    public override void AttackRepel()
    {
        LookPlayer();
        if (transform.localScale.x > 0)
        {
            rb.AddForce(Vector2.left * hitForce, ForceMode2D.Impulse);
            return;
        }
        rb.AddForce(Vector2.right * hitForce, ForceMode2D.Impulse);

    }
    public override void MoveCharacter()
    {
        if (LookPlayer() == "right")
        {
            moveDirection = 1;
            transform.localScale = new Vector3(moveDirection, 1, 1);
            transform.position = new Vector3(transform.position.x + moveDirection * moveSpeed, transform.position.y, transform.position.z);
        }
        else if (LookPlayer() == "left")
        {
            moveDirection = -1;
            transform.localScale = new Vector3(moveDirection, 1, 1);
            transform.position = new Vector3(transform.position.x + moveDirection * moveSpeed, transform.position.y, transform.position.z);
        }


    }

    //看向玩家
    private string LookPlayer()
    {
        //玩家在右侧 怪物的朝向为右
        if (GameManager.Instance.PlayerPosition().x - transform.position.x > 0)
        {
            transform.localScale = new Vector2(1, 1);
            return "right";
        }
        transform.localScale = new Vector2(-1, 1);
        return "left";

    }

}
